package com.uzhie.web.controller.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uzhie.exception.BaseDataException;
import com.uzhie.exception.UserException;
import com.uzhie.util.ConstantKit;
import com.uzhie.util.SessionManager;
import com.uzhie.util.TreeUtil;
import com.uzhie.web.anno.Auth;
import com.uzhie.web.bean.PageBean;
import com.uzhie.web.bean.PayloadBean;
import com.uzhie.web.controller.http.comm.CommController;
import com.uzhie.web.module.BaseData;
import com.uzhie.web.module.Catalog;
import com.uzhie.web.module.Role;
import com.uzhie.web.module.User;
import com.uzhie.web.service.BaseDataService;
import com.uzhie.web.service.CatalogService;
import com.uzhie.web.service.RoleService;
import com.uzhie.web.service.UserService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户
 * Created by lilongfei on 2018/7/13.
 */

@Controller
@RequestMapping(value = "user")
public class UserController extends CommController {


    @Autowired
    UserService userService;
    @Autowired
    CatalogService catalogService;
    @Autowired
    RoleService roleService;
    @Autowired
    BaseDataService baseDataService;

    @Autowired
    private SessionManager<User> sessionManager;

    public UserController() {

    }

    /**
     * 用户登录防范
     *
     * @param body userName 用户登录名
     *             password 用户密码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "login")
    public PayloadBean userLogin(@RequestBody(required = false) JSONObject body) {
        try {
            User user = userService.userLogin
                    (body.getString("username"), body.getString("password"));
            //用户登录成功后 , 插入session,供后面的功能使用
            sessionManager.set(user.getCode(), user);
            List<BaseData> roleType = baseDataService.queryList(ConstantKit.BASEDATA.ROLETYPE.getType() + "", ConstantKit.STATUS.IS_AVAILABLE, new RowBounds(1, 10000));

            List<String> categorys = new ArrayList<>();
            categorys.add(ConstantKit.BASEDATA.VEHICLE.getType() + "");
            categorys.add(ConstantKit.BASEDATA.COLOR.getType() + "");
            categorys.add(ConstantKit.BASEDATA.FACTORY.getType() + "");
            categorys.add(ConstantKit.BASEDATA.WARNING.getType() + "");
            categorys.add(ConstantKit.BASEDATA.EQUIP.getType() + "");
            Map<String, List<BaseData>> baseDatas = baseDataService.queryListByTypes(categorys, 1, new RowBounds(1, 1000));
            user.setRoleType(roleType);
            user.setBaseDatas(baseDatas);
            user.setLevel(user.getRoles().get(0).getLevel());
            logger.info(body.getString("username") + "成功登录");
            return buildResponse(user);
        } catch (UserException | IllegalArgumentException | BaseDataException e) {
            return buildResponse(null, body.getString("username") + "登录异常:" + e.getMessage());
        }
    }

    /**
     * 根据条件查询用户列表
     *
     * @param body
     * @param pageBean
     * @return
     */
    @Auth
    @ResponseBody
    @RequestMapping(value = "queryList")
    public PayloadBean queryList(@RequestBody(required = false) JSONObject body, @RequestBody(required = false) PageBean pageBean) {
        List<User> users = null;
        try {
            //如果需要分页,需要先设置当前页
            users = userService.queryUserList
                    (body.getString("departId"), body.getString("username"), body.getString("realName"),
                            body.getString("deptName"), body.getString("roleName"),
                            body.getString("startTime"), body.getString("endTime"),
                            pageBean.getRowBounds());
            logger.trace("查询结果 : " + users.size() + "条");
            //拼装result
            return buildResponseWithPage(users, pageBean);
        } catch (IllegalArgumentException | UserException e) {
            return buildResponseWithPage(null, pageBean, "查询失败:" + e.getMessage());
        }
    }

    /**
     * 查询所有目录节点,包含车辆目录
     *
     * @return
     */
    @Auth
    @ResponseBody
    @RequestMapping(value = "querySysCatalog")
    public PayloadBean querySysCatalog(@RequestBody(required = false) JSONObject obj) {
        //通过当前用户所属部门的根节点,迭代下属所有目录节点
        List<Catalog> catalogs = catalogService.selectCatalogToBinding();
        return buildResponse(catalogs.get(0));
    }


    /**
     * 查询所有目录节点,不包含车辆目录 非管理功能
     *
     * @return
     */
    @Auth
    @ResponseBody
    @RequestMapping(value = "selectCatalogByDepart")
    public PayloadBean selectCatalogByDepart(@RequestBody(required = false) JSONObject obj) {
        String catalogId = obj.getString("catalogId");
        //通过当前用户所属部门的根节点,迭代下属所有目录节点
        List<Catalog> catalogs = catalogService.selectCatalogByDepart(catalogId);
        if (catalogs.size() > 0) return buildResponse(new TreeUtil(catalogs).buildTreeByTop().get(0));
        return buildResponse(new ArrayList<>());
    }

    /**
     * 查询所有目录节点,不包含车辆目录 管理功能
     *
     * @return
     */
    @Auth
    @ResponseBody
    @RequestMapping(value = "selectCatalogByDepartForAdmin")
    public PayloadBean selectCatalogByDepartForAdmin(@RequestBody(required = false) JSONObject obj) {
        String catalogId = obj.getString("catalogId");
        //通过当前用户所属部门的根节点,迭代下属所有目录节点
        List<Catalog> catalogs = catalogService.selectCatalogByDepartForAdmin(catalogId);
        if (catalogs.size() > 0) return buildResponse(new TreeUtil(catalogs).buildTreeByTop().get(0));
        return buildResponse(new ArrayList<>());
    }

    /**
     * 查询所有的角色
     *
     * @return
     */
    @Auth
    @ResponseBody
    @RequestMapping(value = "queryRoles")
    public PayloadBean queryRoles(@RequestBody(required = false) JSONObject obj, @RequestBody(required = false) PageBean pageBean) {
        Integer level = obj.getInteger("level");
        List<Role> roles = roleService.selectAllRoleByCondition(null, null, null, null, null, level, pageBean);
        return buildResponseWithPage(roles, pageBean);
    }

    /**
     * 新增用户
     *
     * @param body 用户属性
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addUser")
    public PayloadBean addUser(@RequestBody(required = false) JSONObject body) {
        try {
            userService.addUser(JSON.toJavaObject(body, User.class));
            return buildResponse(null);
        } catch (UserException | IllegalArgumentException e) {
            return buildResponse(null, "添加失败:" + e.getMessage());
        }
    }

    /**
     * 设置用户状态 状态见 {@link ConstantKit}
     *
     * @return
     */
    @Auth
    @ResponseBody
    @RequestMapping(value = "updateStatus")
    public PayloadBean updateStatus(@RequestBody(required = false) JSONObject body) {
        try {
            List<User> users = JSONArray.parseArray(body.getString("list"), User.class);
            int status = body.getInteger("status");
            userService.updateUserStatusByList(users, status);
            return buildResponse(null);
        } catch (UserException | IllegalArgumentException e) {
            return buildResponse(null, "更新状态失败:" + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     *
     * @param body 用户属性
     * @return
     */
    @Auth
    @ResponseBody
    @RequestMapping(value = "updateUser")
    public PayloadBean updateUser(@RequestBody(required = false) JSONObject body) {
        try {
            userService.updateUser(JSON.toJavaObject(body, User.class));
            logger.trace(body.getString("username") + "修改登录");
            return buildResponse(null);
        } catch (IllegalArgumentException e) {
            return buildResponse(null, body.getString("username") + "修改失败: " + e.getMessage());
        }
    }

    /**
     * 绑定用户与角色关系
     *
     * @param body userId 需要绑定对象的用户ID
     *             userName 需要绑定的对象的
     *             roles 需要绑定的角色对象
     * @return
     */
    @Auth
    @ResponseBody
    @RequestMapping(value = "bindRoles")
    public PayloadBean bindRoles(@RequestBody(required = false) JSONObject body) {
        try {
            userService.bindRole
                    (body.getString("userId"), body.getString("username"),
                            JSONObject.parseArray(body.getString("roles"), Role.class));
            return buildResponse(null);
        } catch (IllegalArgumentException | UserException e) {
            return buildResponse(null, "绑定角色失败:" + e.getMessage());
        }
    }

    /**
     * 绑定用户与车辆关系
     *
     * @param body userID 需要绑定的用户对象id
     *             userName 需要绑定的用户对象登录名称
     *             roles 需要绑定的角色对象列表
     * @return
     */
    @Auth
    @ResponseBody
    @RequestMapping(value = "bindVehicles")
    public PayloadBean bindVehicles(@RequestBody(required = false) JSONObject body) {
        try {
            userService.bindVehicle
                    (body.getString("userId"), body.getString("username"),
                            JSONObject.parseArray(body.getString("catalogs"), Catalog.class));
            return buildResponse(null);
        } catch (IllegalArgumentException | UserException e) {
            return buildResponse(null, "绑定车辆失败:" + e.getMessage());
        }
    }


    /**
     * 修改用户密码
     *
     * @param body userId 用户Id
     *             oldPwd 老密码
     *             password 新密码
     * @return
     */
    @Auth
    @ResponseBody
    @RequestMapping(value = "updatePwd")
    public PayloadBean updatePwd(@RequestBody(required = false) JSONObject body) {
        try {
            userService.updatePassword
                    (body.getString("userId"), body.getString("oldPwd"),
                            body.getString("password"));
            return buildResponse(null);
        } catch (IllegalArgumentException | UserException e) {
            return buildResponse(null, "修改用户密码失败:" + e.getMessage());
        }
    }

    /**
     * 用户注销
     *
     * @param body userId 用户id
     * @return
     */
    @Auth
    @ResponseBody
    @RequestMapping(value = "logout")
    public PayloadBean logout(@RequestBody(required = false) JSONObject body) {
        String userId = body.getString("userId");
        if (userId != null) {
            sessionManager.delete(userId);
            return buildResponse(null);
        } else
            return buildResponse(null, UserException.Status.USER_ISNULL);
    }


}
